﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogic;

namespace Private
{
    public partial class EditProfile : System.Web.UI.Page
    {

        #region Properties

        string username;
        MembershipUser paramUser; //user to view profile
        MembershipUser currentUser; //currently logged user
        ProfileCommon userProfile;
        bool isCurrentUserAdmin;
        string[] paramUserRoles;

        #endregion

        #region PageEvents

        protected void Page_PreInit(object sender, EventArgs e)
        {
            username = Request.QueryString[QueryStringConstants.Username];

            if (String.IsNullOrEmpty(username))
            {
                Response.Redirect("~/Main.aspx");
            }

            currentUser = Membership.GetUser();
            paramUser = Membership.GetUser(username);

            if (paramUser == null)
            {
                Session[Constants.Session.ErrorMessage] = Constants.Error.InvalidUser;
                Server.Transfer("~/Error.aspx");
            }

            isCurrentUserAdmin = Roles.IsUserInRole(Constants.Roles.Admin);
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            if (isCurrentUserAdmin && currentUser.UserName != username)
            {
                pnlAdmin.Visible = true;

                paramUserRoles = Roles.GetRolesForUser(username);

                foreach (string role in Roles.GetAllRoles())
                {
                    pnlRoles.Controls.Add(new CheckBox { Text = role, Checked = paramUserRoles.Contains(role) });
                    pnlRoles.Controls.Add(new Literal { Text = "<br />" });
                }
            }

            if (currentUser.UserName == username || isCurrentUserAdmin)
            {
                pnlMain.Visible = true;
                pnlDenied.Visible = false;

                lbUsername.Text = username;
                txtNewEmail.Text = paramUser.Email;

                txtNewSecretQuestion.Text = paramUser.PasswordQuestion;

                revNewPassword.ValidationExpression = ".{" + Membership.Provider.MinRequiredPasswordLength + ",}";
                revNewPassword.ErrorMessage = "Minimum password length is " + Membership.Provider.MinRequiredPasswordLength + " characters";

                revNewPasswordConfirm.ValidationExpression = revNewPassword.ValidationExpression;
                revNewPasswordConfirm.ErrorMessage = revNewPassword.ErrorMessage;
            }
            else
            {
                pnlMain.Visible = false;
                pnlDenied.Visible = true;
            }

            userProfile = (ProfileCommon) ProfileCommon.Create(username);

            txtFirstName.Text = userProfile.Names.FirstName;
            txtLastName.Text = userProfile.Names.LastName;
            cbNamesPublic.Checked = userProfile.Names.isPublic;

            txtICQ.Text = userProfile.ContactInfo.ICQ;
            txtMSN.Text = userProfile.ContactInfo.MSN;
            cbContactInfoPublic.Checked = userProfile.ContactInfo.isPublic;

            txtBirthDate.Text = userProfile.BirthInfo.BirthDate.ToString();

            txtWebsite.Text = userProfile.Website;

            this.Title = "Edit profile for user " + username;
        }

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            //set the values that has been changed by activate/deactivate buttons
            if (isCurrentUserAdmin && currentUser.UserName != username)
            {
                lbIsActive.Text = paramUser.IsApproved ? "active" : "deactivated";

                if (paramUser.IsApproved)
                {
                    btnActivateUser.Visible = false;
                    btnDeactivateUser.Visible = true;
                }
                else
                {
                    btnActivateUser.Visible = true;
                    btnDeactivateUser.Visible = false;
                }
            }
        }

        #endregion

        #region ControlEvents

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (tbProfileInfo.ActiveTabIndex == 0)
            {
                #region PersonalInformation

                userProfile.Names.FirstName = txtFirstName.Text;
                userProfile.Names.LastName = txtLastName.Text;
                userProfile.Website = txtWebsite.Text;
                userProfile.BirthInfo.isPublic = cbBirthDatePublic.Checked;
                userProfile.Names.isPublic = cbNamesPublic.Checked;
                lbError.Visible = true;
                lbError.Text = "Profile information saved";

                #endregion
            }
            else if (tbProfileInfo.ActiveTabIndex == 1)
            {
                #region ContactInformation

                userProfile.ContactInfo.ICQ = txtICQ.Text;
                userProfile.ContactInfo.MSN = txtMSN.Text;
                userProfile.ContactInfo.isPublic = cbContactInfoPublic.Checked;
                lbError.Visible = true;
                lbError.Text = "Profile information saved";

                #endregion
            } 
            else
            {
                #region AccountSettings

                bool changePassword = false;
                bool changeQuestionAndAnswer = false;
                bool changeEmail = false;

                bool passwordVerified = false;

                lbError.Visible = true;



                //check what has been changed
                #region CheckChanges

                if (txtNewPassword.Text != "" || txtNewPasswordConfirm.Text != "")
                {
                    if (txtNewPassword.Text == txtNewPasswordConfirm.Text)
                    {
                        if (txtCurrentPassword.Text != "")
                        {
                            changePassword = true;
                        }
                        else
                        {
                            lbError.Text = "Current password required for password change.";
                            return;
                        }
                    }
                    else
                    {
                        lbError.Text = "Password does not match with confirm password.";
                        return;
                    }
                }

                if (txtNewSecretAnswer.Text.Trim() != "")
                {
                    if (txtNewSecretQuestion.Text.Trim() != "")
                    {
                        changeQuestionAndAnswer = true;
                    }
                    else
                    {
                        lbError.Text = "Question required for answer change.";
                        return;
                    }
                }

                if (txtNewEmail.Text.Trim() != paramUser.Email)
                {
                    changeEmail = true;
                }

                #endregion



                //change what has to be changed
                #region SubmitChanges

                if (changePassword)
                {
                    if (txtCurrentPassword.Text == "")
                    {
                        lbError.Text = "Password required for password change.";
                        return;
                    }

                    if (paramUser.ChangePassword(txtCurrentPassword.Text, txtNewPassword.Text))
                    {
                        lbError.Text = "Password changed successfully. ";
                        txtCurrentPassword.Text = txtNewPassword.Text;
                        passwordVerified = true;
                    }
                    else
                    {
                        if (!Membership.ValidateUser(paramUser.UserName, txtCurrentPassword.Text))
                        {
                            lbError.Text = "Incorrect current password.";
                            return;

                        }
                        else
                        {
                            lbError.Text = "Error while trying to change password.";
                            return;
                        }
                    }
                }

                if (changeQuestionAndAnswer)
                {
                    if (txtCurrentPassword.Text == "")
                    {
                        lbError.Text = "Password required for secret question change.";
                        return;
                    }

                    if (paramUser.ChangePasswordQuestionAndAnswer(txtCurrentPassword.Text, txtNewSecretQuestion.Text, txtNewSecretAnswer.Text))
                    {
                        lbError.Text += "Secret question changed successfully. ";
                        passwordVerified = true;
                    }
                    else
                    {
                        if (!Membership.ValidateUser(paramUser.UserName, txtCurrentPassword.Text))
                        {
                            lbError.Text = "Incorrect current password.";
                            return;
                        }
                        else
                        {
                            lbError.Text += "Error while trying to change secret question and answer.";
                            return;
                        }
                    }
                }

                if (changeEmail)
                {
                    if (!isCurrentUserAdmin && txtCurrentPassword.Text == "")
                    {
                        lbError.Text = "Password required for e-mail change.";
                        return;
                    }

                    if (passwordVerified || isCurrentUserAdmin || Membership.ValidateUser(paramUser.UserName, txtCurrentPassword.Text))
                    {
                        paramUser.Email = txtNewEmail.Text.Trim();
                        lbError.Text += "E-mail changed successfully. ";
                    }
                    else
                    {
                        lbError.Text = "Incorrect current password.";
                        return;
                    }
                }

                //update user if anything that requires update has been changed
                if (changeEmail)
                {
                    Membership.UpdateUser(paramUser);
                }

                #endregion


                if (lbError.Text == "")
                {
                    lbError.Text = "Profile information saved";
                }

                #endregion
            }

            userProfile.Save();
            Cache.Remove(Constants.Cache.Users);
        }

        protected void btnDeleteUser_Click(object sender, EventArgs e)
        {
            Membership.DeleteUser(username, true);

            Cache.Remove(Constants.Cache.Users);

            Response.Redirect("~/Admin/UserManagement.aspx");
        }

        protected void btnDeactivateUser_Click(object sender, EventArgs e)
        {
            paramUser.IsApproved = false;
            Membership.UpdateUser(paramUser);

            Cache.Remove(Constants.Cache.Users);
        }

        protected void btnActivateUser_Click(object sender, EventArgs e)
        {
            paramUser.IsApproved = true;
            Membership.UpdateUser(paramUser);

            Cache.Remove(Constants.Cache.Users);
        }

        protected void btnSaveRoles_Click(object sender, EventArgs e)
        {
            List<string> rolesToAdd = new List<string>();
            List<string> rolesToRemove = new List<string>();

            foreach (Control c in pnlRoles.Controls)
            {
                CheckBox cb = c as CheckBox;
                if (cb != null)
                {
                    if (cb.Checked && !paramUserRoles.Contains(cb.Text))
                    {
                        rolesToAdd.Add(cb.Text);
                    }
                    else if (paramUserRoles.Contains(cb.Text))
                    {
                        rolesToRemove.Add(cb.Text);
                    }
                }
            }

            if (rolesToAdd.Count > 0)
            {
                Roles.AddUserToRoles(username, rolesToAdd.ToArray());
            }
            if (rolesToRemove.Count > 0)
            {
                Roles.RemoveUserFromRoles(username, rolesToRemove.ToArray());
            }

            lbUserStatus.Visible = true;
            lbUserStatus.Text = "Roles saved successfully";
        }

        #endregion

        protected void tbProfileInfo_ActiveTabChanged(object sender, EventArgs e)
        {
            lbError.Visible = false;
        }
}
}